#ifndef EMS_WEB_SERVER_H
#define EMS_WEB_SERVER_H

#include <string>
#include <atomic>
#include <chrono>
#include <thread>
#include <memory>

namespace ems {
namespace device { class DeviceManager; }
namespace service { class DispatchService; class DataCollector; class DataUploader; }
namespace web {

class WebServer {
public:
    WebServer(int port = 8080, const std::string& configRoot = ".");
    ~WebServer();

    bool start();
    void stop();
    bool isRunning() const { return running_; }

    void setDispatchService(service::DispatchService* dispatchService);
    void setDeviceManager(device::DeviceManager* deviceManager);
    void setDataCollector(service::DataCollector* dataCollector);
    void setDataUploader(service::DataUploader* dataUploader);
    
private:
    void serverThread();
    void handleConnection(int clientSocket);
    std::string handleRequest(const std::string& request);
    bool handleSseRequest(int clientSocket, const std::string& method,
                          const std::string& pathWithQuery, const std::string& rawRequest);
    bool handleConsoleSseRequest(int clientSocket, const std::string& method,
                                 const std::string& pathWithQuery);
    std::string getResource(const std::string& path);
    std::string getMimeType(const std::string& path);
    std::string handleApiRequest(const std::string& method,
                                 const std::string& path,
                                 const std::string& rawRequest);
    std::string handleWebSocketRequest(const std::string& request);
    long getSystemUptime();
    std::string getCurrentTimestamp();
    
    int port_;
    int serverSocket_;
    std::atomic<bool> running_;
    std::thread serverThread_;
    std::atomic<bool> shouldStop_;
    std::string configRoot_;
    service::DispatchService* dispatchService_{nullptr};
    device::DeviceManager* deviceManager_{nullptr};
    service::DataCollector* dataCollector_{nullptr};
    service::DataUploader* dataUploader_{nullptr};
    std::chrono::steady_clock::time_point startTime_;
};

} // namespace web
} // namespace ems

#endif // EMS_WEB_SERVER_H
